package org.summer.lawyer.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.lawyer.constant.enums.WalletActionEnums;
import org.summer.lawyer.domain.UserWallet;
import org.summer.lawyer.domain.bo.userwallet.UserWalletBo;
import org.summer.lawyer.domain.bo.userwalletlog.UserWalletLogBo;
import org.summer.lawyer.domain.vo.brokerageconfig.BrokerageConfigVo;
import org.summer.lawyer.domain.vo.brokeragerecord.BrokerageRecordVo;
import org.summer.lawyer.domain.vo.paytransfer.PayTransferVo;
import org.summer.lawyer.domain.vo.userwallet.UserWalletVo;
import org.summer.lawyer.mapper.UserWalletMapper;
import org.summer.lawyer.service.IBrokerageConfigService;
import org.summer.lawyer.service.IUserWalletLogService;
import org.summer.lawyer.service.IUserWalletService;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 用户钱包Service业务层处理
 *
 * @author summer
 * @date 2024-06-27
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements IUserWalletService {

    private final IBrokerageConfigService brokerageConfigService;
    private final IUserWalletLogService userWalletLogService;

    /**
     * 查询用户钱包
     *
     * @param walletId 主键
     * @return 用户钱包
     */
    @Override
    public UserWalletVo selectUserWalletVoById(Long walletId) {
        UserWalletVo vo = baseMapper.selectVoById(walletId);
        if (vo != null) {
            BrokerageConfigVo brokerageConfigVo = brokerageConfigService.selectOneBrokerageConfigVo();
            vo.setWithdrawFeePercent(brokerageConfigVo.getWithdrawFeePercent());
            vo.setWithdrawMinPrice(brokerageConfigVo.getWithdrawMinPrice());
        }
        return vo;
    }

    /**
     * 查询用户钱包,未找到是，默认初始化
     */
    @Lock4j(keys = {"#wxUserId"}, acquireTimeout = 1000, expire = 10000)
    @Override
    public UserWalletVo selectUserWalletVoByUserId(Long wxUserId) {
        LambdaQueryWrapper<UserWallet> queryWrapper = Wrappers.<UserWallet>lambdaQuery();
        queryWrapper.eq(UserWallet::getWxUserId, wxUserId);
        UserWalletVo vo = baseMapper.selectVoOne(queryWrapper, false);
        if (vo == null) {
            vo = initWallet(wxUserId);
        }
        BrokerageConfigVo brokerageConfigVo = brokerageConfigService.selectOneBrokerageConfigVo();
        vo.setWithdrawFeePercent(brokerageConfigVo.getWithdrawFeePercent());
        vo.setWithdrawMinPrice(brokerageConfigVo.getWithdrawMinPrice());
        return vo;
    }

    /**
     * 分页查询用户钱包列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户钱包分页列表
     */
    @Override
    public TableDataInfo<UserWalletVo> selectPageList(UserWalletBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<UserWallet> lqw = buildQueryWrapper(bo);
        Page<UserWalletVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户钱包列表
     *
     * @param bo 查询条件
     * @return 用户钱包列表
     */
    @Override
    public List<UserWalletVo> selectUserWalletVoList(UserWalletBo bo) {
        LambdaQueryWrapper<UserWallet> lqw = Wrappers.lambdaQuery();
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<UserWallet> buildQueryWrapper(UserWalletBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<UserWallet> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getWxUserId() != null, UserWallet::getWxUserId, bo.getWxUserId());
        lqw.eq(bo.getWalletIncome() != null, UserWallet::getWalletIncome, bo.getWalletIncome());
        lqw.eq(bo.getWalletExpense() != null, UserWallet::getWalletExpense, bo.getWalletExpense());
        lqw.eq(bo.getBalanceFee() != null, UserWallet::getBalanceFee, bo.getBalanceFee());
        lqw.eq(bo.getFrozenAmount() != null, UserWallet::getFrozenAmount, bo.getFrozenAmount());
        return lqw;
    }

    /**
     * 新增用户钱包
     *
     * @param bo 用户钱包
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(UserWalletBo bo) {
        UserWallet add = MapstructUtils.convert(bo, UserWallet.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtil.date());
        add.setUpdateTime(DateUtil.date());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setWalletId(add.getWalletId());
        }
        return flag;
    }

    /**
     * 修改用户钱包
     *
     * @param bo 用户钱包
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(UserWalletBo bo) {
        UserWallet update = MapstructUtils.convert(bo, UserWallet.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtil.date());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(UserWallet entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户钱包信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 初始化钱包
     */
    @Override
    public UserWalletVo initWallet(Long wxUserId) {
        UserWalletBo bo = new UserWalletBo();
        bo.setWxUserId(wxUserId);
        bo.setWalletIncome(0L);
        bo.setWalletExpense(0L);
        bo.setBalanceFee(0L);
        bo.setFrozenAmount(0L);
        insertByBo(bo);
        return selectUserWalletVoByUserId(wxUserId);
    }

    /**
     * 钱包支出
     */
    @Override
    public void walletExpense(PayTransferVo vo) {
        UserWalletVo walletVo = selectUserWalletVoByUserId(vo.getUserId());
        UserWallet userWallet = new UserWallet();
        userWallet.setWalletId(walletVo.getWalletId());
        Long preAmount = walletVo.getBalanceFee();
        Long expense = walletVo.getWalletExpense() + vo.getAmount();
        Long balanceFee = walletVo.getBalanceFee() - vo.getAmount();
        userWallet.setWalletExpense(expense);
        userWallet.setBalanceFee(balanceFee);
        LambdaUpdateWrapper<UserWallet> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(UserWallet::getWalletId, walletVo.getWalletId());
        baseMapper.update(userWallet, updateWrapper);
        //增加流水记录
        UserWalletLogBo walletLogBo = new UserWalletLogBo();
        walletLogBo.setWxUserId(vo.getUserId());
        walletLogBo.setTargetUuid(vo.getWithdrawNumber());
        walletLogBo.setTargetType("提现");
        walletLogBo.setPreAmount(preAmount);
        walletLogBo.setAmount(vo.getAmount());
        walletLogBo.setPostAmount(balanceFee);
        walletLogBo.setActionType(WalletActionEnums.WITHDRAW.getCode());
        walletLogBo.setRemark("提现");
        userWalletLogService.insertByBo(walletLogBo);
    }

    /**
     * 钱包收入
     */
    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public void walletIncome(BrokerageRecordVo vo) {
        UserWalletVo walletVo = selectUserWalletVoByUserId(vo.getWxUserId());
        UserWallet userWallet = new UserWallet();
        userWallet.setWalletId(walletVo.getWalletId());
        Long preAmount = walletVo.getBalanceFee();
        Long income = walletVo.getWalletIncome() + vo.getAmount();
        Long balanceFee = walletVo.getBalanceFee() + vo.getAmount();
        userWallet.setWalletIncome(income);
        userWallet.setBalanceFee(balanceFee);
        LambdaUpdateWrapper<UserWallet> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(UserWallet::getWalletId, walletVo.getWalletId());
        baseMapper.update(userWallet, updateWrapper);
        //增加流水记录
        UserWalletLogBo walletLogBo = new UserWalletLogBo();
        walletLogBo.setWxUserId(vo.getWxUserId());
        walletLogBo.setTargetUuid(String.valueOf(vo.getId()));
        walletLogBo.setTargetType("佣金收入");
        walletLogBo.setPreAmount(preAmount);
        walletLogBo.setAmount(vo.getAmount());
        walletLogBo.setPostAmount(balanceFee);
        walletLogBo.setActionType(WalletActionEnums.INCOME.getCode());
        walletLogBo.setRemark(StrUtil.format("{} 佣金收入", vo.getTitle()));
        userWalletLogService.insertByBo(walletLogBo);

    }
}
